package scm.erp.sale.order.controller;
import com.github.pagehelper.PageInfo;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import scm.erp.core.domain.Pg;
import scm.erp.core.domain.Ret;
import scm.erp.sale.order.domain.Order;
import scm.erp.sale.order.enums.OrderStatus;
import scm.erp.sale.order.service.OrderService;
import java.util.Collections;
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    private final OrderService service;
    public  OrderController(OrderService service) {
        this.service = service;
    }
    /**
     * 查询单条（未用）
     *
     * @param id 数据ID
     * @return PlanVo 查询结果
     */
    @GetMapping("/one/{id}")
    public Ret<Order.Vo> one(@PathVariable String id) {
        Order.Vo OrderVo = service.one(id);
        return Ret.ok(OrderVo);
    }
    /**
     * 新增
     *
     * @param vo 新增数据
     * @return 数据ID
     */
    @PostMapping("/insert")
    public Ret<String> insert(
            @Validated @RequestBody Order.Vo vo) {
        String id = service.insert(vo);
        return Ret.ok(id);
    }

    /**
     * 更新
     *
     * @param vo 更新数据
     * @return 更新结果
     */
    @PostMapping("/update")
    public Ret<Boolean> update(
            @Validated @RequestBody Order.Vo vo) {
        Boolean ret = service.update(vo);
        return Ret.ok(ret);
    }

    @PostMapping("/page")
    public Ret<Object> page(
            @Validated @RequestBody Pg<Order.Entity, Order.SearchVo> pg) {
        PageInfo<Order.Entity> pageInfo = pg
                .startPage()
                .selectPage(() -> this.service.list(pg.getPageData()))
                .closePage()
                .getPageInfo();
        return Ret.ok(pageInfo);
    }
//     单条修改（补充接口）
    @PostMapping("/status/{id}")
    public Ret<Integer> updateSingleStatus(
            @PathVariable @NotBlank(message = "id不能为空") String id,
            @RequestParam @NotNull(message = "状态类型不能为空") String statusType
    ) {
        Order.OrderStatusUpdateRequest request = new Order.OrderStatusUpdateRequest();
        request.setOrderStatus(OrderStatus.valueOf(statusType));
        request.setIds(Collections.singletonList(id));
        int updateCount = this.service.updateOrderStatus(request);
        return Ret.ok(updateCount);
    }


//     批量修改（主接口）
    @PostMapping("/status/batch")
    public Ret<Integer> batchUpdateStatus(@RequestBody @Valid Order.OrderStatusUpdateRequest request) {
        int updateCount = this.service.updateOrderStatus(request);
        return Ret.ok(updateCount);
    }
}
